# 作者: YYJ
# 2025年07月04日15时17分40秒
# 2486249622@qq.com
import time

import pygame
from plane_sprites import *

class PlaneGame(object):
    """飞机大战主游戏"""

    def __init__(self):
        """游戏初始化"""
        print("游戏初始化")

        # 创建游戏窗口
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        # 创建游戏时钟
        self.clock = pygame.time.Clock()
        # 创建精灵和精灵组
        self.__create_sprites()

        # 定时创建敌机
        pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)
        # 定时发射子弹
        pygame.time.set_timer(HERO_FIRE_EVENT, 300)

    def __create_sprites(self):
        """创建精灵和精灵组"""
        # 背景组
        bg1 = BackGround()
        bg2 = BackGround(True)
        self.back_group = pygame.sprite.Group(bg1, bg2)
        # 敌机组
        self.enemy_group = pygame.sprite.Group()
        # 英雄组
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)

    def start_game(self):
        """开始游戏"""
        print("开始游戏")

        while True:
            # 设置刷新频率
            self.clock.tick(FPS)
            # 事件监听
            self.__event_handler()
            # 碰撞检测
            self.__check_collide()
            # 更新精灵组
            self.__update_sprites()
            # 更新显示
            pygame.display.update()

    def __event_handler(self):
        """事件监听"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                PlaneGame.__game_over()

            elif event.type == CREATE_ENEMY_EVENT:
                # 创建敌机
                enemy = Enemy()
                self.enemy_group.add(enemy)
            elif event.type == HERO_FIRE_EVENT:
                self.hero.fire()

        # 获取按键
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_RIGHT]:    # 向右
            self.hero.speed = 8
        elif keys_pressed[pygame.K_LEFT]:   # 向左
            self.hero.speed = -8
        else:
            self.hero.speed = 0

    def __check_collide(self):
        """碰撞检测"""
        # 子弹摧毁敌机
        pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
        # 敌机撞英雄
        enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)

        if len(enemies) > 0:
            self.hero.kill()
            m = "./sound/use_bomb.wav"
            pygame.mixer.music.load(m)
            pygame.mixer.music.play()
            time.sleep(2)
            PlaneGame.__game_over()

    def __update_sprites(self):
        """更新精灵组"""
        for group in [self.back_group, self.enemy_group, self.hero_group, self.hero.bullets]:
            group.update()
            group.draw(self.screen)

    @staticmethod
    def __game_over():
        """游戏结束"""
        print("游戏结束")
        pygame.quit()
        exit()

if __name__ == '__main__':
    pygame.init()
    game = PlaneGame()
    game.start_game()
